package com.etoak.controller;




import com.etoak.entity.User;

import com.etoak.util.ValidatorUtil;
import com.etoak.service.UserService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j//public static final Logger log = LoggerFactory.getLogger(UserController.class);
public class UserController {
    @Autowired
    UserService userService;


    //public static final Logger log = LoggerFactory.getLogger(UserController.class);






    /**
     * 查询用户接口 get/user/get?id=1
     * @param id
     *
     */
    @GetMapping("/get")
    public User getUser(int id){
        return userService.getUser(id);
    }

    /**
     * REST风格请求查询用户接口
     * get/user/1（获取用户为1的用户资源）
     */
    @GetMapping("/{id}")
    public User getRestUser(@PathVariable int id) {
        //System.out.println("id="+id);
        log.info("id - {}",id);

        return userService.getUser(id);
    }

    /**
     * 添加用户
     * POST/user
     */
    @PostMapping
    public Object addUser(@RequestBody User user) {
       //System.out.println(user);

        Map<String,Object> result = new HashMap<>();

        //校验
        try{
            ValidatorUtil.validate(user);
        }catch(RuntimeException e){
            log.error(e.getMessage());

            result.put("code",201);
            result.put("msg", e.getMessage());
            return result;

        }

        result.put("code",200);
        result.put("msg","success");
        return result;
    }


    /**
     * 更新用户
     * PUT /user/{id}  参数 json form表单
     */
    @PutMapping("/{id}")
    public Object updataUser(@PathVariable int id,@RequestBody User user) {
        //根据id先查询是否存在，没有用户直接返回给前端
        System.out.println("id="+id);
        System.out.println("user="+user);

        Map<String,Object> result = new HashMap<>();
        result.put("code",200);
        result.put("msg","success");
        return result;


    }


    /**
     * 根据id删除用户接口
     *
     */
    @DeleteMapping("/{id}")
    public Object deleteUser(@PathVariable int id) {
        System.out.println("id="+id);

        Map<String,Object> result = new HashMap<>();
        result.put("code",200);
        result.put("msg","success");
        return result;
    }






}
